<template>
  <div>
    <div ref="chartRef" class="h-500px" v-show="!loading"></div>
    <div class="h-500px" v-if="loading">
      <q-inner-loading :showing="loading">
        <q-spinner-gears size="3em" color="primary" />
      </q-inner-loading>
    </div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts/core'
import type { TooltipComponentOption, GridComponentOption } from 'echarts/components'
import { TitleComponent, TooltipComponent, GridComponent } from 'echarts/components'
import type { BarSeriesOption } from 'echarts/charts'
import { BarChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { creationChartDataBar } from 'src/service/api'
import { onMounted, ref } from 'vue'

echarts.use([TooltipComponent, TitleComponent, GridComponent, BarChart, CanvasRenderer])

type EChartsOption = echarts.ComposeOption<
  TooltipComponentOption | GridComponentOption | BarSeriesOption
>

const chartRef = ref<HTMLElement>()

const loading = ref(false)

onMounted(() => {
  if (!chartRef.value) {
    return
  }
  loading.value = true
  const myChart = echarts.init(chartRef.value)
  creationChartDataBar().then(({ data, error }) => {
    loading.value = false
    if (!error) {
      const option: EChartsOption = {
        title: {
          text: '最近文章阅读量',
        },
        tooltip: {
          trigger: 'axis',

          axisPointer: {
            type: 'shadow',
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: [
          {
            type: 'category',
            data: data.dataX,
            axisTick: {
              alignWithLabel: true,
            },
            axisLabel: {
              formatter(value) {
                let str = value
                if (value.length > 8) {
                  str = value.slice(0, 7) + '...'
                }
                return str
              },
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
          },
        ],
        series: [
          {
            name: '阅读量',
            type: 'bar',
            barWidth: '60%',
            data: data.dataY,
          },
        ],
      }
      myChart.setOption(option)
    }
  })
})
</script>

<style scoped></style>
